/**
 * 
 */
package com.yqwh.coder.jpush;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.jpush.api.push.PushResult;

/**
 * @author hejie
 * @date 2018年3月21日
 */
public class Main {

	static final Logger log = LoggerFactory.getLogger(Main.class);

	/**
	 * 入口：向用户发送消息
	 */
	public void sendPushMessage() {
		List<PushUser> pushUsers = null;
		PushMessage msg = null;
		sendMsgByrangeType(pushUsers, msg);
	}

	/**
	 * 根据设备范围推送tag通知（tag是用户的id） 注：捕捉异常继续发送都是为了不影响推送给其他的用户
	 * 
	 * @param connection
	 * @param msg
	 */
	private void sendMsgByrangeType(List<PushUser> pushUsers, PushMessage msg) {
		PushResult pushResult_android = null;
		PushResult pushResult_ios = null;
		String rangeType = msg.getRangeType();
		for (PushUser pr : pushUsers) {
			try {
				msg.setTag(String.valueOf(pr.getId()));
				if ("android".equalsIgnoreCase(rangeType)) {
					pushResult_android = JpushUtil.buildPushAndroidTagMessage(msg);
					JpushUtil.closeJpushClient();
				} else if ("ios".equalsIgnoreCase(rangeType)) {
					pushResult_ios = JpushUtil.buildPushIosTagNotification(msg);
					JpushUtil.closeJpushClient();
				} else if ("android,ios".equalsIgnoreCase(rangeType) || "ios,android".equals(rangeType)) {
					try {
						pushResult_android = JpushUtil.buildPushAndroidTagMessage(msg);
					} catch (Exception e) {
						log.error(e.getMessage(), e);
						msg.setState(PushMessage.SEND_FAIL);// 推送失败
						msg.setReturnMsg(e.getMessage());
						continue;
					} finally {
						pushResult_ios = JpushUtil.buildPushIosTagNotification(msg);
						JpushUtil.closeJpushClient();
					}
				}
				if (pushResult_ios != null) {
					if (pushResult_ios.isResultOK()) {
						msg.setState(PushMessage.SEND_SUCCESS);// 推送成功
						msg.setReturnMsg(pushResult_ios.getOriginalContent());
					} else {
						msg.setState(PushMessage.SEND_FAIL);// 推送失败
						msg.setReturnMsg(pushResult_ios.getOriginalContent());
					}
				}
				if (pushResult_android != null) {
					if (pushResult_android.isResultOK()) {
						msg.setState(PushMessage.SEND_SUCCESS);// 推送成功
						msg.setReturnMsg(pushResult_android.getOriginalContent());
					} else {
						msg.setState(PushMessage.SEND_FAIL);// 推送失败
						msg.setReturnMsg(pushResult_android.getOriginalContent());
					}
				}
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				msg.setState(PushMessage.SEND_FAIL);// 推送失败
				msg.setReturnMsg(e.getMessage());
				continue;
			}
		}
	}

}
